package com.zhu.config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.stereotype.Controller;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

@Configuration
@PropertySource("classpath:db.properties") // 添加此行！
@ComponentScan(
        basePackages = "com.zhu",
        excludeFilters = @ComponentScan.Filter(
                type = FilterType.ANNOTATION,
                classes = Controller.class
        )
)
@MapperScan("com.zhu.dao")
public class ApplicationConfig {

    // 数据源配置
    @Bean
    public DataSource dataSource(
            @Value("${jdbc.driver}") String driver,
            @Value("${jdbc.url}") String url,
            @Value("${jdbc.username}") String username,
            @Value("${jdbc.password}") String password
    ) throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(driver);
        dataSource.setJdbcUrl(url);
        dataSource.setUser(username);
        dataSource.setPassword(password);

// 添加以下关键参数 ⬇️
        dataSource.setInitialPoolSize(5); // 初始连接数
        dataSource.setMinPoolSize(5); // 最小连接数
        dataSource.setMaxPoolSize(20); // 最大连接数
        dataSource.setAcquireIncrement(5); // 连接耗尽时一次性新建连接数
        dataSource.setMaxIdleTime(1800); // 空闲连接超时时间(秒)
        dataSource.setCheckoutTimeout(5000); // 获取连接超时时间(毫秒)
        dataSource.setTestConnectionOnCheckout(true); // 获取连接时验证有效性
        dataSource.setPreferredTestQuery("SELECT 1"); // 连接测试语句

        return dataSource;
    }

    // MyBatis SQL会话工厂
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setDataSource(dataSource);
        return factory;
    }
}